// 全局变量
let selectedFile = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeUploadArea();
    initializeForm();
    initializeProcessModeToggle();
    
    // 当前页面没有systemStatus元素，暂时不加载系统状态
    // if (document.getElementById('systemStatus')) {
    //     loadSystemStatus();
    // }
});

// 初始化上传区域
function initializeUploadArea() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    
    // 设置拖拽事件
    setupDragAndDrop(uploadArea, fileInput);
    
    // 文件选择事件
    fileInput.addEventListener('change', function(e) {
        handleFileSelect(e.target.files[0]);
    });
}

// 设置拖拽功能
function setupDragAndDrop(uploadArea, fileInput) {
    uploadArea.addEventListener('click', function() {
        fileInput.click();
    });
    
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelect(files[0]);
        }
    });
}

// 处理文件选择
function handleFileSelect(file) {
    if (!file) return;
    
    // 验证文件类型
    const fileName = file.name.toLowerCase();
    if (!fileName.endsWith('.xls') && !fileName.endsWith('.xlsx') && !fileName.endsWith('.csv')) {
        showAlert('请选择 .xls、.xlsx 或 .csv 格式的文件', 'danger');
        return;
    }
    
    // 验证文件大小 (10MB)
    if (file.size > 10 * 1024 * 1024) {
        showAlert('文件大小不能超过 10MB', 'danger');
        return;
    }
    
    selectedFile = file;
    displayFileInfo(file);
}

// 显示文件信息
function displayFileInfo(file) {
    const fileInfo = document.getElementById('fileInfo');
    const fileName = document.getElementById('fileName');
    const fileSize = document.getElementById('fileSize');
    const uploadArea = document.getElementById('uploadArea');
    
    fileName.textContent = file.name;
    fileSize.textContent = formatFileSize(file.size);
    fileInfo.style.display = 'block';
    
    // 添加CSS类来调整布局
    uploadArea.classList.add('has-file');
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 重置文件信息
function resetFileInfo() {
    const fileInfo = document.getElementById('fileInfo');
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    
    // 隐藏文件信息
    fileInfo.style.display = 'none';
    
    // 移除CSS类
    uploadArea.classList.remove('has-file');
    
    // 清除文件输入
    fileInput.value = '';
    selectedFile = null;
}

// 初始化表单
function initializeForm() {
    // 统一处理表单
    document.getElementById('excelProcessForm').addEventListener('submit', function(e) {
        e.preventDefault();
        processExcelFile();
    });
}

// 初始化处理模式切换
function initializeProcessModeToggle() {
    const singleMode = document.getElementById('singleMode');
    const multiMode = document.getElementById('multiMode');
    const sheetNamesGroup = document.getElementById('sheetNamesGroup');
    const primarySection = document.getElementById('primarySection');
    const middleSection = document.getElementById('middleSection');
    const startCol = document.getElementById('startCol');
    const endCol = document.getElementById('endCol');
    
    // 学部选择事件监听
    primarySection.addEventListener('change', function() {
        if (this.checked) {
            // 小学部：设置默认列范围
            startCol.value = 'C';
            endCol.value = 'L';
        }
    });
    
    middleSection.addEventListener('change', function() {
        if (this.checked) {
            // 初中部：默认单工作表，设置默认列范围和起始行
            singleMode.checked = true;
            sheetNamesGroup.style.display = 'none';
            startCol.value = 'B';
            endCol.value = 'M';
            document.getElementById('startRow').value = '1'; // 初中部默认起始行为2
        }
    });
    
    singleMode.addEventListener('change', function() {
        if (this.checked) {
            sheetNamesGroup.style.display = 'none';
        }
    });
    
    multiMode.addEventListener('change', function() {
        if (this.checked) {
            sheetNamesGroup.style.display = 'block';
        }
    });
}

// 统一处理Excel文件
async function processExcelFile() {
    if (!selectedFile) {
        showAlert('请先选择文件', 'warning');
        return;
    }
    
    // 获取处理模式和学部选择
    const isMultiMode = document.getElementById('multiMode').checked;
    const schoolSection = document.querySelector('input[name="schoolSection"]:checked').value;
    const dataMode = document.querySelector('input[name="dataMode"]:checked').value;
    let sheetNames = document.getElementById('sheetNames').value.trim();
    const startCol = document.getElementById('startCol').value.trim();
    const endCol = document.getElementById('endCol').value.trim();
    const startRow = parseInt(document.getElementById('startRow').value);
    const endRow = parseInt(document.getElementById('endRow').value);
    
    // 初中部自动设置为"初中部"工作表
    if (schoolSection === 'middle') {
        sheetNames = '初中部'; // 设置为"初中部"工作表
    }
    
    // 验证基本参数
    if (!startCol || !endCol || !startRow || !endRow) {
        showAlert('请填写完整的处理参数', 'warning');
        return;
    }
    
    if (startRow > endRow) {
        showAlert('起始行不能大于结束行', 'warning');
        return;
    }
    
    // 多工作表模式下验证工作表名称
    if (isMultiMode && !sheetNames) {
        showAlert('多工作表模式下请填写工作表名称', 'warning');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', selectedFile);
    formData.append('startCol', startCol);
    formData.append('endCol', endCol);
    formData.append('startRow', startRow);
    formData.append('endRow', endRow);
    formData.append('schoolSection', schoolSection);
    formData.append('dataMode', dataMode);
    
    // 如果是多工作表模式或初中部，添加工作表名称参数
    if ((isMultiMode && sheetNames) || schoolSection === 'middle') {
        formData.append('sheetNames', sheetNames);
    }
    
    try {
        const sectionText = schoolSection === 'primary' ? '小学部' : '初中部';
        const modeText = isMultiMode ? '多工作表' : '单工作表';
        const progressMessage = `正在处理${sectionText}${modeText}文件...`;
        showProgress(progressMessage);
        
        const response = await fetch('/upload/process', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        hideProgress();
        
        if (result.success) {
            const sectionText = schoolSection === 'primary' ? '小学部' : '初中部';
            const modeText = isMultiMode ? '多工作表' : '单工作表';
            const resultTitle = `${sectionText}${modeText}处理完成`;
            showResult(result, resultTitle);
        } else {
            showAlert(result.message || '处理失败', 'danger');
        }
    } catch (error) {
        hideProgress();
        showAlert('网络错误: ' + error.message, 'danger');
    }
}


// 显示进度
function showProgress(message) {
    const progressContainer = document.getElementById('progressContainer');
    const progressText = document.getElementById('progressText');
    const progressBar = document.getElementById('progressBar');
    
    progressText.textContent = message;
    progressBar.style.width = '0%';
    progressContainer.style.display = 'block';
    
    // 模拟进度
    let progress = 0;
    const interval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress > 90) progress = 90;
        progressBar.style.width = progress + '%';
    }, 200);
    
    // 保存interval ID以便后续清除
    progressContainer.dataset.intervalId = interval;
}

// 隐藏进度
function hideProgress() {
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    
    // 清除进度动画
    if (progressContainer.dataset.intervalId) {
        clearInterval(progressContainer.dataset.intervalId);
    }
    
    // 完成进度
    progressBar.style.width = '100%';
    
    setTimeout(() => {
        progressContainer.style.display = 'none';
    }, 500);
}

// 显示结果
function showResult(result, title) {
    const resultContainer = document.getElementById('resultContainer');
    const resultContent = document.getElementById('resultContent');
    
    // 重置文件信息显示
    resetFileInfo();
    
    let html = `
        <div class="alert alert-success">
            <h6><i class="fas fa-check-circle me-2"></i>${title}</h6>
            <p class="mb-2">${result.message}</p>
        </div>
        <div class="row">
    `;
    
    // 不显示处理统计信息
    
    html += '</div>';
    
    // 显示下载链接
    if (result.downloadUrl) {
        html += `
            <div class="mt-3">
                <a href="${result.downloadUrl}" class="btn btn-success me-2" download>
                    <i class="fas fa-download me-2"></i>下载处理结果
                </a>

            </div>
        `;
    }
    
    // 显示处理详情
    if (result.processedSheets) {
        html += `
            <div class="mt-3">
                <h6>已处理的工作表:</h6>
                <div class="badge bg-success me-1">${result.processedSheets}</div>
            </div>
        `;
    }
    
    if (result.notFoundSheets) {
        html += `
            <div class="mt-2">
                <h6>未找到的工作表:</h6>
                <div class="badge bg-warning me-1">${result.notFoundSheets}</div>
            </div>
        `;
    }
    
    resultContent.innerHTML = html;
    resultContainer.style.display = 'block';
    

    
    // 滚动到结果区域
    resultContainer.scrollIntoView({ behavior: 'smooth' });
}

// 显示警告信息
function showAlert(message, type = 'info') {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            <i class="fas fa-${getAlertIcon(type)} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    // 在页面顶部显示警告
    const container = document.querySelector('.main-container');
    const alertDiv = document.createElement('div');
    alertDiv.innerHTML = alertHtml;
    container.insertBefore(alertDiv, container.firstChild);
    
    // 自动隐藏
    setTimeout(() => {
        const alert = alertDiv.querySelector('.alert');
        if (alert) {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }
    }, 5000);
}

// 获取警告图标
function getAlertIcon(type) {
    const icons = {
        'success': 'check-circle',
        'danger': 'exclamation-triangle',
        'warning': 'exclamation-circle',
        'info': 'info-circle'
    };
    return icons[type] || 'info-circle';
}

// 加载系统状态
async function loadSystemStatus() {
    try {
        const response = await fetch('/upload/status');
        const status = await response.json();
        displaySystemStatus(status);
    } catch (error) {
        const systemStatusElement = document.getElementById('systemStatus');
        if (systemStatusElement) {
            systemStatusElement.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    无法获取系统状态: ${error.message}
                </div>
            `;
        }
    }
}

// 显示系统状态
function displaySystemStatus(status) {
    const systemStatus = document.getElementById('systemStatus');
    if (!systemStatus) {
        return;
    }
    
    let html = '<div class="row">';
    
    // 上传目录状态
    html += `
        <div class="col-md-6 mb-3">
            <div class="card bg-light">
                <div class="card-body">
                    <h6><i class="fas fa-folder-upload me-2"></i>上传目录</h6>
                    <p class="mb-1">路径: <code>${status.uploadDir}</code></p>
                    <p class="mb-1">状态: <span class="status-badge ${status.uploadDirExists ? 'bg-success' : 'bg-danger'}">
                        ${status.uploadDirExists ? '正常' : '不存在'}
                    </span></p>
                    ${status.uploadFileCount !== undefined ? `<p class="mb-0">文件数量: ${status.uploadFileCount}</p>` : ''}
                </div>
            </div>
        </div>
    `;
    
    // 输出目录状态
    html += `
        <div class="col-md-6 mb-3">
            <div class="card bg-light">
                <div class="card-body">
                    <h6><i class="fas fa-folder-open me-2"></i>输出目录</h6>
                    <p class="mb-1">路径: <code>${status.outputDir}</code></p>
                    <p class="mb-1">状态: <span class="status-badge ${status.outputDirExists ? 'bg-success' : 'bg-danger'}">
                        ${status.outputDirExists ? '正常' : '不存在'}
                    </span></p>
                    ${status.outputFileCount !== undefined ? `<p class="mb-0">文件数量: ${status.outputFileCount}</p>` : ''}
                </div>
            </div>
        </div>
    `;
    
    html += '</div>';
    
    // 错误信息
    if (status.error) {
        html += `
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle me-2"></i>
                ${status.error}
            </div>
        `;
    }
    
    systemStatus.innerHTML = html;
}

// 清理文件
async function cleanupFiles() {
    const keepDays = parseInt(document.getElementById('keepDays').value);
    
    if (!keepDays || keepDays < 1) {
        showAlert('请输入有效的保留天数', 'warning');
        return;
    }
    
    if (!confirm(`确定要清理 ${keepDays} 天前的文件吗？此操作不可撤销。`)) {
        return;
    }
    
    try {
        const response = await fetch(`/upload/cleanup?keepDays=${keepDays}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showAlert(`清理完成，删除了 ${result.deletedCount} 个文件`, 'success');
            // 重新加载系统状态
            loadSystemStatus();
        } else {
            showAlert(result.message || '清理失败', 'danger');
        }
    } catch (error) {
        showAlert('网络错误: ' + error.message, 'danger');
    }
}

// 标签页切换时重新加载状态 - 由于当前页面没有status-tab元素，暂时注释掉
// const statusTab = document.getElementById('status-tab');
// if (statusTab) {
//     statusTab.addEventListener('shown.bs.tab', function() {
//         loadSystemStatus();
//     });
// }